package fr.idak.spring.tiles.web.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import fr.idak.spring.tiles.hibernate.entity.Language;
import fr.idak.spring.tiles.service.LanguageService;
import fr.idak.spring.tiles.web.controller.Constante.URL;
import fr.idak.spring.tiles.web.controller.Constante.VIEW;
import fr.idak.spring.tiles.web.security.CustomUserDetails;


@Controller
public class WelcomeController {
	
	@Autowired
	private LanguageService languageService;
	
	@RequestMapping(value=URL.WELCOME, method=RequestMethod.GET)
	public String welcome(Model model){
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		CustomUserDetails userDetails = null;
		Object principal = authentication.getPrincipal();
		if(principal instanceof CustomUserDetails){
			userDetails = (CustomUserDetails) principal;
		}
		model.addAttribute("userDetails", userDetails);
		
		return VIEW.WELCOME;
	}
	
	@RequestMapping(value=URL.LANGUAGE, method=RequestMethod.GET)
	public String language(){
		return VIEW.LANGUAGE;
	}
	
	
	@RequestMapping(value = "allLanguage", method = RequestMethod.POST)
    @ResponseBody
    public JTableJSONResponse<Language> getLanguages(@RequestParam int jtStartIndex, @RequestParam int jtPageSize, HttpSession session) {
    	List<Language> languages =languageService.getLanguagesByIndex(jtStartIndex, jtPageSize);
    	int maxRecord = 0;
    	if(session.getAttribute("maxRecords")== null){
    		maxRecord = languageService.countRecords();
    		session.setAttribute("maxRecords", maxRecord);
    	}else{
    		maxRecord = (int) session.getAttribute("maxRecords");
    	}
        return new JTableJSONResponse<Language>("OK",languages,maxRecord);
	}
}
